<?php
namespace app\api\controller\wanlshop;

use addons\wanlshop\library\WanlSdk\Common;
use app\api\model\wanlshop\Hxq as HxqModel;
use app\api\model\wanlshop\HxqUser;
use app\common\controller\Api;
use think\Cache;
use think\Db;
use think\Exception;
use think\Hook;

/**
 * WanlShop核销券接口
 */
class Hxq extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['*'];
    //获取核销券列表
    public function list(){
        $hxq = HxqUser::alias('hxq_user')->where('hxq_user.user_id',$this->auth->id)
            ->orderRaw('CASE WHEN hxq_user.state = "normal" THEN 0 ELSE 1 END')
            ->with(['shop','hxq','good'])

            ->paginate();
        return $this->success('获取成功',$hxq);
    }
    //获取核销券详情
    public function detail(){
        $id = $this->request->request('id');
        $hxq = HxqUser::alias('hxq_user')
            ->where('hxq_user.id',$id)
            ->where('hxq_user.user_id',$this->auth->id)
            ->with('shop','hxq')
            ->find();
        if($hxq){
            return $this->success('获取成功',$hxq);
        }else{
            return $this->error('获取失败');
        }

    }

    // 核销券
    public function writeoff()
    {
        $id = $this->request->request('id');
        $key = "shop_hxq_".$id;
        if (Cache::store('redis')->has($key)){
            $this->error('您已核销过该券');
        }else{
            Cache::store('redis')->set($key, $id, 3);
        }
        if (!$this->auth->isLogin()){
            $this->error('请先登录');
        }
        // 验证店铺是否是自己的
        $shop_id = (new \app\api\model\wanlshop\Shop)->where(['user_id'=>$this->auth->id])->value('id');
        if (!$shop_id){
            $this->error('无核销权限');
        }
        $hxq = HxqUser::alias('hxq_user')
            ->where('hxq_user.id',$id)
            ->find();
        if (!$hxq){
            $this->error('该券不存在');
        }
        if ($hxq->state != 'normal'){
            $this->error('该券已核销');
        }
        if ($shop_id != $hxq->shop_id){
            $this->error('该券不属于您的店铺');
        }
        if ($hxq->expire_time < time()){
           $this->error('该券已过期');
        }
        if($hxq){
            $hxq->state = 'hidden'; // 已使用
            $hxq->hx_time = time(); // 核销时间
            $hxq->updatetime = time(); // 核销时间
            $hxq->hx_user_id = $this->auth->id; // 核销人
            $hxq->save();
            $this->success('核销成功');
        }
        $this->error('核销失败');
    }

    // 店铺核销券列表
    public function shop_hxq_index()
    {
        $id = $this->request->param('id');
        // 获取列表
        $list = (new HxqModel)->with('shop')->where(['shop_id'=>$id])->paginate(10);

        $this->success('获取成功',$list);
    }

    // 核销券详情
    public function shop_hxq_detail()
    {
        $hxq_id = $this->request->param('id');
        $hxq = HxqModel::where(['id'=>$hxq_id])->find();
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $id = $hxq['goods_id'];
        // 是否传入商品ID
        $id ? $id : ($this->error(__('非正常访问')));

        $clickid = $this->request->param('clickid'); // 巨量
        $callback = $this->request->param('cili'); // 磁力
        $bxmid = $this->request->param('bxm_id'); // 变现猫
        $event_type = $this->request->param('event_type'); // 事件
        // 设置
        if ($clickid && $event_type){
            $param = [
                'clickId' => $clickid,
                'eventType' => $event_type,
            ];
            $data = [
                'type' => false,
                'goodsId' => $id,
                'appid' => "",
                'source' => '巨量',
            ];
            Hook::listen('tf_statistics',$param,$data);
        }
        if ($callback && $event_type){
            $param = [
                'clickId' => $callback,
                'eventType' => $event_type,
            ];
            $data = [
                'type' => false,
                'goodsId' => $id,
                'appid' => "",
                'source' => '磁力',
            ];
            Hook::listen('tf_statistics',$param,$data);
        }
        if ($bxmid && $event_type){
            $param = [
                'clickId' => $bxmid,
                'eventType' => $event_type,
            ];
            $data = [
                'type' => false,
                'goodsId' => $id,
                'appid' => "",
                'source' => '变现猫',
            ];
            Hook::listen('tf_statistics',$param,$data);
        }

        // 加载商品模型
        $goodsModel = model('app\api\model\wanlshop\Goods');
        // 查询商品
        $goods = $goodsModel
            ->where(['id' => $id])
            ->field('id,category_id,shop_category_id,brand_id,freight_id,shop_id,title,description,image,images,flag,content,category_attribute,activity_type,price,sales,payment,comment,praise,moderate,negative,like,views,status')
            ->find();
        // 浏览+1 & 报错
        if($goods && $goods['status'] == 'normal'){
            // 查询类目
            $goods->category->visible(['id','pid','name']);
            // 查询优惠券
            $goods['coupon'] = $this->queryCoupon($goods['id'], $goods['shop_id'], $goods['shop_category_id'], $goods['price']);
            // 查询是否关注
            $goods['follow'] = $this->isfollow($id);
            // 查询品牌
            $goods->brand->visible(['name']);
            // 查询SKU
            $goods['sku'] = $goods->sku;
            // 查询SPU
            $goods['spu'] = $goods->spu;
            // 查询直播状态
            $goods['isLive'] = model('app\api\model\wanlshop\Live')->where(['shop_id' => $goods['shop_id'], 'state' => 1])->field('id')->find();
            // 查询评论
            $goods['comment_list'] = $goods->comment_list;
            // 获取店铺详情
            $goods->shop;
//                ->visible(['shopname','service_ids','avatar','city','like','score_describe','score_service','score_logistics']);
            // 查询快递 运费ID 商品重量 邮递城市 商品数量
            $goods['freight'] = $this->freight($goods['freight_id']);
            // 查询促销
            $goods['hxq'] = $hxq; //--下个版本更新--// 查询促销
            $goods['promotion'] = $id; //--下个版本更新--
            // 店铺推荐
            $goods['shop_recommend'] = $goodsModel
                ->where(['shop_id' => $goods['shop_id'], 'status' => 'normal']) //还可以使用 , 'flag' => 'recommend'
                ->field('id,title,image,price')
                ->limit(3)
                ->select();
            // 浏览+1
            $goods->setInc('views');
            // 写入访问日志
            $this->addbrowse($goods);
            // 返回结果
            $this->success('返回成功', $goods);
        }else{
            $this->error(__('对不起当前商品不存在或已下架！'));
        }
    }

    /**
     * 查询我的优惠券 内部方法 (跨段存在登录问题，无法解决，暂时复制进来这个方法)
     *
     * @param string $goods_id 商品ID
     * @param string $shop_id 店铺ID
     * @param string $shop_category_id 分类ID
     * @param string $price 价格
     */
    private function queryCoupon($goods_id = null, $shop_id = null, $shop_category_id = null, $price = null)
    {
        $user_coupon = [];
        if ($this->auth->isLogin()) {
            foreach (model('app\api\model\wanlshop\CouponReceive')->where([
                'user_id' => $this->auth->id,
                'shop_id' => $shop_id,
                'limit' => ['<=', intval($price)],
                'state' => '1'
            ])->select() as $row) {
                $user_coupon[$row['coupon_id']] = $row;
            }
        }
        // 开始查询
        $list = [];
        $goods_id = explode(",",$goods_id);
        $shop_category_id = explode(",",$shop_category_id);
        //要追加一个排序 选出一个性价比最高的
        foreach (model('app\api\model\wanlshop\Coupon')->where([
            'shop_id' => $shop_id,
            'limit' => ['<=', intval($price)]
        ])->select() as $row) {
            // 筛选出还未开始的
            if(!($row['pretype'] == 'fixed' && (strtotime($row['startdate']) >= time() || strtotime($row['enddate']) < time()))){
                //追加字段
                $row['choice'] = false;
                // 检查指定的键名是否存在于数组中
                if(array_key_exists($row['id'], $user_coupon)){
                    $row['invalid'] = 0; // 强制转换优惠券状态
                    $row['id'] = $user_coupon[$row['id']]['id'];
                    $row['state'] = true;
                }else{
                    $row['state'] = false;
                }
                // 排除失效优惠券
                if($row['invalid'] == 0){
                    // 高级查询，比较数组，返回交集如果和原数据数目相同则加入
                    if($row['rangetype'] == 'all'){
                        $list[] = $row;
                    }
                    if($row['rangetype'] == 'goods' && count($goods_id) == count(array_intersect($goods_id, explode(",",$row['range'])))){
                        $list[] = $row;
                    }
                    // 1.1.0升级
                    if($row['rangetype'] == 'category'){
                        // 判断优化全类目是否在商品类目中，explode(',', $row['range'])[0] 目的向前兼容
                        if( in_array(explode(',', $row['range'])[0], $shop_category_id) ){
                            $list[] = $row;
                        }
                    }
                }
            }
        }
        return $list;
    }

    /**
     * 获取运费模板和子类 内部方法 -----下个版本完善------
     * @param string $id  运费ID
     * @param string $weigh  商品重量
     * @param string $city  邮递城市
     * @param string $number  商品数量
     */
    private function freight($id = null, $weigh = 0, $city = '北京', $number = 1)
    {
        // 运费模板
        $data = model('app\api\model\wanlshop\ShopFreight')->where('id', $id)->field('id,delivery,isdelivery,name,valuation')->find();
        $data['price'] = 0;
        // 是否包邮:0=自定义运费,1=卖家包邮
        if($data['isdelivery'] == 0){
            // 获取地址编码 1.1.0升级
            $list = model('app\api\model\wanlshop\ShopFreightData')
                ->where([
                    ['EXP', Db::raw('FIND_IN_SET('.model('app\common\model\Area')->get(['name' => $city])->id.', citys)')],
                    'freight_id' => $id
                ])
                ->find();
            // 查询是否存在运费模板数据
            if(!$list){
                $list = model('app\api\model\wanlshop\ShopFreightData')->get(['freight_id' => $id]);
            }

            // 计价方式:0=按件数,1=按重量,2=按体积
            if($data['valuation'] == 0){
                if($number <= $list['first']){
                    $price = $list['first_fee'];
                }else{
                    $price = ceil(($number - $list['first']) / $list['additional']) * $list['additional_fee'] + $list['first_fee'];
                }
            }else{
                $weigh = $weigh * $number; // 订单总重量
                if($weigh <= $list['first']){ // 如果重量小于等首重，则首重价格
                    $price = $list['first_fee'];
                }else{
                    $price = ceil(($weigh - $list['first']) / $list['additional']) * $list['additional_fee'] + $list['first_fee'];
                }
            }
            $data['price'] = $price;
        }
        return $data;
    }
    /**
     * 是否关注商品
     *
     * @ApiSummary  (WanlShop 保存浏览记录)
     * @ApiMethod   (GET)
     *
     * @param string $goods  商品数据
     */
    public function isfollow($goods_id ='')
    {
        $data = false;
        if ($this->auth->isLogin()) {
            $follow = model('app\api\model\wanlshop\GoodsFollow')
                ->where([
                    'user_id' => $this->auth->id,
                    'goods_id' => $goods_id,
                    'goods_type' => 'goods'
                ])
                ->count();
            $data = $follow == 0 ? false : true; //关注
        }
        return $data;
    }

    /**
     * 保存浏览记录
     *
     * @ApiSummary  (WanlShop 保存浏览记录)
     * @ApiMethod   (GET)
     *
     * @param string $goods  商品数据
     */
    public function addbrowse($goods =[])
    {
        //保存浏览记录
        $uuid = $this->request->server('HTTP_UUID');
        if(!isset($uuid)){
            $charid = strtoupper(md5($this->request->header('user-agent').$this->request->ip()));
            $uuid = substr($charid, 0, 8).chr(45).substr($charid, 8, 4).chr(45).substr($charid,12, 4).chr(45).substr($charid,16, 4).chr(45).substr($charid,20,12);
        }
        $recordModel = model('app\api\model\wanlshop\Record');
        $goods_type = 'goods';
        $record = $recordModel
            ->where([
                'uuid' => $uuid,
                'goods_id' => $goods['id'],
                'goods_type' => $goods_type
            ])
            ->find();
        if($record){
            $update['id'] = $record['id'];
            if ($this->auth->isLogin()) {
                $update['user_id'] = $this->auth->id;
            }
            $update['views'] = $record['views'] + 1;
            $record->update($update);
        }else{
            if ($this->auth->isLogin()) {
                $recordModel->user_id = $this->auth->id;
            }
            $recordModel->uuid = $uuid;
            $recordModel->goods_id = $goods['id'];
            $recordModel->goods_type = $goods_type;
            $recordModel->shop_id = $goods['shop_id'];
            $recordModel->category_id = $goods['category']['id'];
            $recordModel->category_pid = $goods['category']['pid'];
            $recordModel->ip = $this->request->ip();
            $recordModel->save();
        }
    }
}